package com.iteaj.demo.server.protocol;

import com.iteaj.demo.server.ServerDemoMessage;
import com.iteaj.demo.server.ServerProtocolType;
import com.iteaj.network.message.DeviceMessageHead;
import com.iteaj.network.server.protocol.PlatformRequestProtocol;
import com.iteaj.network.utils.ByteUtil;
import org.apache.commons.lang3.time.DateFormatUtils;

import java.io.IOException;
import java.net.ProtocolException;
import java.nio.charset.StandardCharsets;
import java.util.Date;

public class PlatformRequestClientDemoProtocol extends PlatformRequestProtocol<ServerDemoMessage> {

    /**
     * 请求内容
     */
    private String content;

    public PlatformRequestClientDemoProtocol(String equipCode, String content) {
        super(equipCode);
        this.content = content;
    }

    @Override
    protected String doGetMessageId() {
        /*此方法后面版本将会废弃*/
        return null;
    }

    /**
     * 在这里构建请求客户端的报文
     * @return
     * @throws IOException
     */
    @Override
    protected ServerDemoMessage doBuildRequestMessage() throws IOException {
        if(getEquipCode() == null || getEquipCode().length() != 6) {
            throw new ProtocolException("设备编号请使用6个字符(字母 + 数字)");
        }

        final byte[] deviceSnMsg = ByteUtil.hexToByte(getEquipCode());
        final byte[] typeMsg = ByteUtil.hexToByte(protocolType().getCode());
        final String messageId = DateFormatUtils.format(new Date(), "yyyyMMddHHmmss");
        final byte[] messageIdMsg = ByteUtil.hexToByte(messageId);

        final byte[] bytes = ByteUtil.hexToByte(content);
        final byte[] message = new byte[11 + bytes.length];

        ByteUtil.addBytes(message, deviceSnMsg, 0);
        ByteUtil.addBytes(message, typeMsg, 3);
        ByteUtil.addBytes(message, messageIdMsg, 4);
        ByteUtil.addBytes(message, bytes, 11);

        DeviceMessageHead head = new DeviceMessageHead(new byte[]{}, messageId, getEquipCode(), protocolType());
        final ServerDemoMessage demoMessage = new ServerDemoMessage(message);
        demoMessage.setHead(head);

        return demoMessage;
    }

    @Override
    protected ServerDemoMessage resolverResponseMessage(ServerDemoMessage message) {
        return null;
    }

    @Override
    public ServerProtocolType protocolType() {
        return ServerProtocolType.PlatformRequest;
    }
}
